#!/usr/bin/env python3
"""
FEC控制器 - 用于控制FEC的开启/关闭和配置
"""

import asyncio
import json
from typing import Optional, Dict, Any, Callable
from dataclasses import dataclass, asdict
from aiortc_custom.fec import FecConfig

@dataclass
class FecControlConfig:
    """FEC控制配置"""
    enabled: bool = True
    fec_type: str = "repetition"  # FEC类型: "repetition", "xor", "reed_solomon"
    k: int = 3  # 原始包数量
    n: int = 6  # 总包数量（包含冗余）
    repair_window: int = 1000  # 修复窗口（毫秒）
    
    def to_fec_config(self) -> FecConfig:
        """转换为FecConfig对象"""
        if not self.enabled:
            return None
        
        # 计算重复因子：对于重复编码，每个原始包应该重复 (n-k)/k 次
        if self.fec_type == "repetition":
            repetition_factor = (self.n - self.k) // self.k if self.k > 0 else 1
        else:
            repetition_factor = 1
        
        return FecConfig(
            fec_type=self.fec_type,
            k=self.k,
            n=self.n,
            repair_window_ms=self.repair_window,
            repetition_factor=repetition_factor
        )
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典"""
        return asdict(self)
    
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> 'FecControlConfig':
        """从字典创建"""
        return cls(**data)

class FecController:
    """FEC控制器"""
    
    def __init__(self, initial_config: Optional[FecControlConfig] = None):
        self.config = initial_config or FecControlConfig()
        self.callbacks: Dict[str, Callable] = {}
        self.stats = {
            "fec_packets_sent": 0,
            "fec_packets_received": 0,
            "packets_repaired": 0,
            "packets_lost": 0,
            "repair_success_rate": 0.0
        }
    
    def register_callback(self, event: str, callback: Callable):
        """注册回调函数"""
        self.callbacks[event] = callback
    
    def _notify(self, event: str, data: Any = None):
        """通知回调函数"""
        if event in self.callbacks:
            try:
                self.callbacks[event](data)
            except Exception as e:
                print(f"[FEC控制器] 回调函数执行错误: {e}")
    
    def enable_fec(self, fec_type: str = "repetition", k: int = 3, n: int = 6):
        """启用FEC"""
        self.config.enabled = True
        self.config.fec_type = fec_type
        self.config.k = k
        self.config.n = n
        
        print(f"[FEC控制器] FEC已启用: 类型={fec_type}, k={k}, n={n}")
        self._notify("fec_enabled", self.config)
    
    def disable_fec(self):
        """禁用FEC"""
        self.config.enabled = False
        print("[FEC控制器] FEC已禁用")
        self._notify("fec_disabled", self.config)
    
    def update_config(self, config: FecControlConfig):
        """更新配置"""
        old_config = self.config
        self.config = config
        
        print(f"[FEC控制器] 配置已更新: 启用={config.enabled}, 类型={config.fec_type}")
        self._notify("fec_config_updated", {"old": old_config, "new": config})
    
    def get_config(self) -> FecControlConfig:
        """获取当前配置"""
        return self.config
    
    def get_fec_config(self) -> Optional[FecConfig]:
        """获取FecConfig对象"""
        return self.config.to_fec_config()
    
    def is_enabled(self) -> bool:
        """检查FEC是否启用"""
        return self.config.enabled
    
    def update_stats(self, **kwargs):
        """更新统计信息"""
        for key, value in kwargs.items():
            if key in self.stats:
                self.stats[key] = value
        
        # 计算修复成功率
        if self.stats["fec_packets_received"] > 0:
            self.stats["repair_success_rate"] = (
                self.stats["packets_repaired"] / self.stats["fec_packets_received"]
            )
        
        self._notify("stats_updated", self.stats)
    
    def get_stats(self) -> Dict[str, Any]:
        """获取统计信息"""
        return self.stats.copy()
    
    def reset_stats(self):
        """重置统计"""
        self.stats = {
            "fec_packets_sent": 0,
            "fec_packets_received": 0,
            "packets_repaired": 0,
            "packets_lost": 0,
            "repair_success_rate": 0.0
        }
        self._notify("stats_reset", self.stats)
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典"""
        return {
            "config": self.config.to_dict(),
            "stats": self.stats
        }
    
    def from_dict(self, data: Dict[str, Any]):
        """从字典加载"""
        if "config" in data:
            self.config = FecControlConfig.from_dict(data["config"])
        if "stats" in data:
            self.stats.update(data["stats"])

# 全局FEC控制器实例
_global_fec_controller: Optional[FecController] = None

def get_global_fec_controller() -> FecController:
    """获取全局FEC控制器"""
    global _global_fec_controller
    if _global_fec_controller is None:
        _global_fec_controller = FecController()
    return _global_fec_controller

def set_global_fec_controller(controller: FecController):
    """设置全局FEC控制器"""
    global _global_fec_controller
    _global_fec_controller = controller

def enable_fec(fec_type: str = "repetition", k: int = 3, n: int = 6):
    """启用FEC（全局函数）"""
    controller = get_global_fec_controller()
    controller.enable_fec(fec_type, k, n)

def disable_fec():
    """禁用FEC（全局函数）"""
    controller = get_global_fec_controller()
    controller.disable_fec()

def is_fec_enabled() -> bool:
    """检查FEC是否启用（全局函数）"""
    controller = get_global_fec_controller()
    return controller.is_enabled()

def get_fec_config() -> Optional[FecConfig]:
    """获取FEC配置（全局函数）"""
    controller = get_global_fec_controller()
    return controller.get_fec_config()

def get_fec_stats() -> Dict[str, Any]:
    """获取FEC统计（全局函数）"""
    controller = get_global_fec_controller()
    return controller.get_stats()

if __name__ == "__main__":
    # 测试FEC控制器
    print("=== FEC控制器测试 ===")
    
    controller = FecController()
    
    # 测试启用FEC
    print("\n1. 启用FEC")
    controller.enable_fec("repetition", k=3, n=6)
    print(f"FEC状态: {controller.is_enabled()}")
    print(f"FEC配置: {controller.get_fec_config()}")
    
    # 测试更新统计
    print("\n2. 更新统计")
    controller.update_stats(fec_packets_sent=100, fec_packets_received=95, packets_repaired=10)
    stats = controller.get_stats()
    print(f"FEC统计: {stats}")
    
    # 测试禁用FEC
    print("\n3. 禁用FEC")
    controller.disable_fec()
    print(f"FEC状态: {controller.is_enabled()}")
    print(f"FEC配置: {controller.get_fec_config()}")
    
    print("\n✅ FEC控制器测试完成")